package jersey.czjug;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;

/**
 * MessageBeanWriter implementing the serialization of list of properties into
 * a stream of type text/plain.
 */
@Provider
public class PropertyListWriter implements MessageBodyWriter<List<PropertyBean>> {
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
                               MediaType mediaType) {
        // Should check the generic type as well to make sure it List<PropertyBean>
        // not just any List. Anyway, that code is more complex and out of scope of this
        // lab.
        return MediaType.TEXT_PLAIN_TYPE.equals(mediaType) && List.class.isAssignableFrom(type);
    }

    public long getSize(List<PropertyBean> t, Class<?> type, Type genericType,
                        Annotation[] annotations, MediaType mediaType) {
        // can return -1 if the size cannot be easily determined
        return -1;
    }

    public void writeTo(List<PropertyBean> t, Class<?> type, Type genericType,
                        Annotation[] annotations, MediaType mediaType,
                        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        StringBuffer result = new StringBuffer();
        for (PropertyBean propertyBean : t) {
            // could delegate to the writer for individual properties,
            // but not doing it for the sake of simplicity
            result.append(propertyBean.toString()).append('\n');
        }
        entityStream.write(result.toString().getBytes());
    }
}
